package com.umessage.hotel.service.impl;

import java.security.InvalidParameterException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSortedSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.umessage.common.service.RedissonService;
import com.umessage.hotel.model.FormModel;
import com.umessage.hotel.service.FormService;

@Service("formService")
public class FormServiceImpl implements FormService {

	@Autowired
	private RedissonService redissonService;
	
	@Override
	public void saveFormId(String openid, FormModel form) {

		if (StringUtils.isBlank(openid) || form == null) {
			throw new InvalidParameterException("openid or form is null");
		}

		RSortedSet<FormModel> formidSet = redissonService.<FormModel>getRSortedSet("wx_formid_" + openid);
		formidSet.add(form);
	}

	@Override
	public void saveFormIdList(String openid, List<FormModel> list) {

		if (StringUtils.isBlank(openid) || list == null || list.size() == 0) {
			throw new InvalidParameterException("openid or list is null");
		}

		RSortedSet<FormModel> formidSet = redissonService.<FormModel>getRSortedSet("wx_formid_" + openid);
		formidSet.addAll(list);
	}
	
	@Override
	public String getValidFormId(String openid) {
		RSortedSet<FormModel> formidSet = redissonService.<FormModel>getRSortedSet("wx_formid_" + openid);

		FormModel invalid = null;
		if (formidSet != null) {
			long now = System.currentTimeMillis();
			Iterator<FormModel> it = formidSet.iterator();

			while (it.hasNext()) {
				FormModel model = it.next();
				if (model.getExpire() > now) {
					invalid = model;
					it.remove();
					break;
				} else {
					it.remove();
				}
			}
		}

		if (invalid != null) {
			return invalid.getFormId();
		}
		return null;
	}

}
